class Solution
{
public:
    int minCost(string colors, vector<int> &neededTime)
    {
        int cost = 0;
        int i = 0;
        int n = colors.size();
        while (i < n)
        {
            char color = colors[i];
            int partTotalCost = neededTime[i];
            int partMax = neededTime[i];
            int nextI = i + 1;
            while (nextI < n)
            {
                if (colors[i] == colors[nextI])
                {
                    partTotalCost += neededTime[nextI];
                    partMax = max(partMax, neededTime[nextI]);
                    ++nextI;
                }
                else
                {
                    break;
                }
            }
            cost += (partTotalCost - partMax);
            i = nextI;
        }
        return cost;
    }
};